<?php

namespace Home\Controller;

use Org\Util\AEHttp;
use Think\Controller;
use Think\Model;

class UserController extends Controller {

    //完善个人信息
    public function edit($shopName="",$realName="",$phone="",$province="",$city="",$street=""){
        if(IS_POST){
            $userid = session("userid");
            $data = array('realName'=>$realName,'phone'=>$phone,'province'=>$province,'city'=>$city,'street'=>$street,'shopName'=>$shopName,'createdate'=>NOW_TIME,'logindate'=>NOW_TIME);
            $map = array('id'=>$userid);
            M('buyers')->where($map)->save($data);

            $dataAddr = array('uid'=>$userid,'name'=>$realName,'phone'=>$phone,'province'=>$province,'city'=>$city,
                'street'=>$street,'shopName'=>$shopName,'createdate'=>NOW_TIME,'lastupdate'=>NOW_TIME);
            M('addr')->add($dataAddr);
            session('userphone',$phone);
            $this->redirect("index/cart");
        }
        $this->display();
    }

    //跳转进入微信授权页面
    public function jumpWXlogin() {
        // $appid = "wx9b58617b10123d97";
        $appid = C("WX_APPID");

        if(APP_STATUS=="product"){
            header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=http://m.shiguo365.com/index.php/Home/User/oauth2&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
        }
        if(APP_STATUS=="staging"){
            header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=http://mdev.shiguo365.com/index.php/Home/User/oauth2&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");
        }
    }

    //微信授权会跳页面
    public function oauth2($code) {

        if(isset($code)){
            if(APP_STATUS=='dev'){
                $openid='oe75lxJVse7dMXQRFaqcTWQN5S5Qw';
            }else{
                $appid = C("WX_APPID");
                $appsecret =C("WX_APPSECRET");

                //获取openid
                $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
                $result = $this->https_request($url);

                //echo $result;
                $WXOPEN = json_decode($result, true);
                $token = $WXOPEN["access_token"];

                $openid = $WXOPEN["openid"];
                $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$token&openid=$openid&lang=zh_CN";
                $user =(array) json_decode($this->https_request($url));
                session('userlogo',$user['headimgurl']);
                session('wxuser',$user);
            }
            $map['openid']=$openid;
            $AeHttp= new AEHttp('shiguo');
            $param['openid']=$openid;
            $res=$AeHttp->postapi('.wxfilter.login1st',$param);
            session('USER',$res['user']);
            session('userphone',$res['user']['phone']);
            session('useropenid',$openid);
            session('lastlogin',time());
            if(isset($res['errno'])){
                $this->error('登陆出错，正在处理中......',U(''),30);
            }
            switch($res['status']){
                case 0:

                    //跳转首页
                    session('userid',$res['user']['id']);
                    session('username',$res['user']['username']);
                    $this->redirect('Index/index');
                    break;
                case 1:
                    $this->redirect('User/underreview',array('username'=>$res['user']['username']));
                    break;
                case 2:
                    //跳转手机号绑定页面
                    $this->redirect('User/accountimprove');
                    break;
                case 3:
                    //跳转账号密码设置页面
                    $this->redirect('User/password');
                    break;
                case 4:
                    //跳转世果引导页
                    $this->redirect('User/welcome');
                    break;
                case 5:
                    //跳转世果账号登录
                    $this->redirect('User/login');
                    break;
                case 6:
                    //跳转注册页面
                    $this->redirect('User/register');
                    break;
            }
//            $uid=M('buyers')->where($map)->getField('id');
//            $userphone=M('buyers')->where($map)->getField('phone');
//            $user_info=M('buyers')->where($map)->find();
//            if($user_info==null){
//                //首次进入微信商城
//                $this->display('User/login');
//            }else{
//                session('userlogo',$user['headimgurl']);
//                session('useropenid',$openid);
//                session('userid',$user_info['id']);
//                session('wxuser',$user);
//                session('userphone',$user_info['phone']);
//                $this->redirect('Index/index');
//                //微信商城老用户
//            }
//            if($uid){
//                session('userlogo',$user['headimgurl']);
//                session('useropenid',$openid);
//                session('userid',$uid);
//                session('wxuser',$user);
//                session('userphone',$userphone);
//                $this->redirect("index/index");
//            }else{
//                //如果没有注册，自动注册
//                session('userlogo',$user['headimgurl']);
//                $data['openid']=$openid;
//                $data['nickName']=$user['nickname'];
//                $data['createdate']=NOW_TIME;
//                $uid=M('buyers')->add($data);
//                session('useropenid',$openid);
//                session('userid',$uid);
//                session('userphone',$userphone);
//                session('wxuser',$user);
//                $this->redirect("index/index");
//            }

        }
    }

    //退出清理session
    public function loginout() {
        session_unset();
        $this->success("用户退出成功", U('index/index'));
    }

    //http工具
    function https_request($url, $data = null) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     * 审核中
     */
    public function underreview($username){
        $this->username=$username;
        $this->display();
    }

    /**
     * 账号完善
     */
    public function accountimprove(){
        $this->validTime=session('SmsLimitTime');
        $this->display();
    }

    /**
     * 登录
     */
    public function login($phone=null,$code=null){
        if(IS_POST){
            $param['phone']=$phone;
            $param['code']=$code;
            $param['openid']=session('useropenid');
            $AeHttp= new AEHttp('shiguo');
            $res=$AeHttp->postapi('.wxfilter.loginIn',$param);
            if(isset($res['errno'])){
                switch($res['errno']) {
                    case -1006:
                        $this->error("验证码不正确",U('',array('phone'=>$phone)));
                        break;
                    case -1007:
                        $this->error("验证码不正确",U('',array('phone'=>$phone)));
                        break;
                    default:
                        $this->error("信息不正确",U('',array('phone'=>$phone)));
                        break;

                }
            }
            switch($res['status']){
                case 6:
                    $this->redirect('User/register',array('username'=>$phone,'code'=>$code));
                    break;
                case 0:
                    session('userid',$res['user']['id']);
                    session('username',$res['user']['username']);
                    $this->redirect('Index/index');
                    break;
                case 1:
                    $this->redirect('User/underreview',array('username'=>$res['user']['username']));
                    break;
            }
        }else{
            $this->display();
        }
    }

    /**
     * 账号密码设置
     */
    public function password($username=null,$password=null){
        if(IS_POST){
            $param['phone']=$username;
            $param['password']=$password;
            $param['openid']=session('useropenid');
            $AeHttp=new AEHttp('shiguo');
            $res=$AeHttp->postapi('.wxfilter.bindUsername',$param);
            if($res['errno']<0){
                $this->error("绑定失败",U('',array('username'=>$username)));
            }else{
                $this->redirect("User/bindsuccess",array('username'=>$username));
            }
        }else{
            $this->display();

        }
    }

    /**
     * 引导页
     */
    public function welcome(){
        $this->display();
    }

    /**
     * 注册页面
     */
    public function register($username=null,$code="",$password=null,$shopName=null,$realName=null,$province=null,$city=null,$street=null){
        if(IS_POST){
            $param['openid']=session('useropenid');
            $param['username']=$username;
            $param['code']=$code;
            $param['password']=$password;
            $param['shopName']=$shopName;
            $param['realName']=$realName;
            $param['province']=$province;
            $param['city']=$city;
            $param['street']=$street;
            $param['source']=3;
            $AeHttp=new AEHttp('shiguo');
            $res=$AeHttp->postapi('.wxfilter.registUsername',$param);
            if(isset($res['errno'])){
                $msg="";
                switch($res['errno']){
                    case -1006:
                        $msg="验证码不正确";
                        break;
                    case -1007:
                        $msg="验证码不正确";
                        break;
                    default:
                        $msg="信息不正确";
                        break;
                }
                $this->error($msg,U('User/register'));
            }else{
                $this->redirect('User/underreview',array('username'=>$username));
            }
        }else{
            $this->code=$code;
            $this->display();
        }
    }

    /**
     * 短信验证码
     * @param $phone
     */
    public function validate($phone){
        $AeHttp= new AEHttp('shiguo');
        $param['mobile']=$phone;
        $param['tpl_id']=17582;
        $param['source']=3;
        $res=$AeHttp->postapi('.user.juheSMS',$param);
        if($res['errno']==0){
            session('SmsLimitTime',time()*1000);
        }
        $this->ajaxReturn($res);
    }

    public function completeUser($phone,$code){

        $map['phone']=$phone;
        $map['code']=$code;
        $map['openid']=session('useropenid');
        $AeHttp= new AEHttp('shiguo');
        $res=$AeHttp->postapi('.wxfilter.completeUser',$map);
        if($res['errno']<0){
            $this->error("验证码不正确",U('User/accountimprove'));
//            $this->redirect('User/accountimprove',array(),2,'验证码不正确');
        }
        if($res['status']===0){
            $this->redirect('Index/index');
        }elseif($res['status']===3){
            $this->redirect('User/password',array('username'=>$phone));
        }
    }
}
